
from spatialindex.spatialindex import *
from spatialindex.storagemanager import *
from spatialindex.rtree import *;
import javax,java, string, jarray
from java.lang import *
import cPickle,zlib

class MyVisitor(IVisitor):
	def visitNode(self,n):
		pass

	def visitData(self,d):
		print "\t OMIM GeneID:",d.getIdentifier()		
		#java.lang.String(d.getData());
		 
		


# this builds an index over 

class GenDB:
	indexID=None
	tree=None


	def __init__(self,dbName=None):
	   if None != dbName:	
		try:
		  	ps = PropertySet();
                        ps.setProperty("FileName", dbName);
                                # .idx and .dat extensions will be added.
                        diskfile = DiskStorageManager(ps);
                        file = RandomEvictionsBuffer(diskfile, 100, java.lang.Boolean(0));
                        ps2 = PropertySet();
			i = java.lang.Integer(1);
			ps2.setProperty("IndexIdentifier", i);
                        self.tree = RTree(ps2, file);
		except:
			pass

	def build(self,dbName,filename,parent):
	
			ps = PropertySet();
			b = Boolean(True)
			ps.setProperty("Overwrite", b);
			ps.setProperty("FileName", dbName);	
			# .idx and .dat extensions will be added.

			i = Integer(4096);
			ps.setProperty("PageSize", i);
			diskfile = DiskStorageManager(ps);
			file = RandomEvictionsBuffer(diskfile, 10, True);

			ps2 = PropertySet();

			f = 0.7;
			ps2.setProperty("FillFactor", f);

			i = Integer(200);
			#ps2.setProperty("IndexCapacity", Integer(10));
			ps2.setProperty("LeafCapacity", i);

			i = Integer(2);
			ps2.setProperty("Dimension", i);

			tree = RTree(ps2, file);
	
			#Data = open(filename,'r')
			#Lines = Data.xreadlines();
			#Lines.readline()
			count=0
			try:
				instream = java.io.FileInputStream(java.io.File(filename))
			except:
				print "File Does not Exist"
				return
			if parent is not None:
				plines = javax.swing.ProgressMonitorInputStream(parent,'Loading File ' + filename, instream)
			else:
				plines=instream
		
			lines=java.io.BufferedReader(java.io.InputStreamReader(plines))
			line = lines.readLine()
	
			while line != None:
			  line = lines.readLine()
			  if line is None:
				break


			  else:
				#for line in Lines:
				Q = string.split(line)
				id = string.split(Q[10],':');
				try:
					id = java.lang.Integer(id[1])		
					x1 = java.lang.Double(java.lang.String(Q[2]))
					y1 = 0.0;   # y coordinates refer to layers, x to sequence coordinates
					x2 = java.lang.Double(java.lang.String(Q[3]))
					y2 = 0.0;
				
					f1 = [x1,y1]; 
					f2 = [x2,y2]; 
#					f1 = jarray.array(f1,java.lang.Double)
#					f2 = jarray.array(f2,java.lang.Double)

					r = Region(f1, f2);
#					data = java.lang.String(r.toString());
					count=count+1
					if 0==count % 10:
						tree.flush()


				 	x = zlib.compress(cPickle.dumps(Q))
					x = java.lang.String(x).getBytes("UTF-8")
					tree.insertData(x, r, id);
					#print "insert ok"

				except:
					import sys
					print sys.exc_info()
					print "error on: ", id


			# since we created a new RTree, the PropertySet that was used to initialize the structure
			# now contains the IndexIdentifier property, which can be used later to reuse the index.
			# (Remember that multiple indices may reside in the same storage manager at the same time
			#  and every one is accessed using its unique IndexIdentifier).
			self.indexID = ps2.getProperty("IndexIdentifier");
			print "Index ID: " , self.indexID;
		
			ret = tree.isIndexValid();
			tree.flush();

			if ret == java.lang.Boolean(1): 
				print "Structure is INVALID!";

			# flush all pending changes to persistent storage (needed since Java might not call finalize when JVM exits).
			self.tree = tree
			



#j=javax.swing.JFrame()
#j.show()
g = GenDB('refseq');

f = open("RegulatoryFeatures.Chr17.gff")

L = f.xreadlines()
vis = MyVisitor();

for line in L:
	q = string.split(line)
	x1 = float(q[4])
	x2 = float(q[5])

	if x1<x2:
		x1=x1-2500
		x2=x2+2500
	else:
		x1=x1+2500
		x2=x2-2500
	


	y1 = 0.0;   # y coordinates refer to layers, x to sequence coordinates
	y2 = 0.0;

	f1 = [x1,y1]; 
	f2 = [x2,y2]; 
	r = Region(f1, f2);
	print q
	g.tree.intersectionQuery(r, vis);



#j.dispose()
